package mweb

import (
	"gitee.com/dennis-mxx/mxx-core/mlogger"
	"github.com/kataras/iris/v12/context"
)

type Actuator struct {
	route        *Route
	interceptors []Interceptor
	ctx          *irisWebApplication
}

func (domain *Actuator) execute(c *context.Context) {
	var requestContext *RequestContext
	defer func() {
		defer func() {
			if error := recover(); error != nil {
				mlogger.Logger.Error(error)
			}
		}()
		if err := recover(); err != nil {
			domain.ctx.exceptionHandler(requestContext, err.(error))
		}
	}()
	ctx := c.Values().Get("RequestContext")
	if ctx != nil {
		requestContext = ctx.(*RequestContext)
		requestContext.Route = *domain.route

	} else {
		requestContext = &RequestContext{
			Application: domain.ctx,
			Ctx:         c,
			Route:       *domain.route,
			Url:         c.Path(),
			ContentType: c.GetHeader("content-type"),
			UserAgent:   c.GetHeader("User-Agent"),
			Method:      c.Method(),
			sess:        domain.ctx.IrisSession,
			Validate:    domain.ctx.Validate,
		}
		c.Values().Set("RequestContext", requestContext)
	}
	requestContext.Println()
	for _, interceptor := range domain.interceptors {
		if !interceptor(requestContext) {
			return
		}
	}
	error, data := domain.route.HandleAdapter(requestContext)
	if error == nil {
		if data != nil {
			requestContext.WriteJSON(data)
		}
	} else {
		domain.ctx.exceptionHandler(requestContext, error)
	}

}
